<?php


namespace App\Http\Controllers\Api;

use App\Businesses\BusinessState;
use App\Http\Requests\ApiV2\AddressRequest;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Member\Services\UserService;
use App\Services\Member\Models\Address;
use Illuminate\Http\Request;

class AddressController extends BaseController
{


    /**
     * @var UserService
     */
    protected $userService;
    protected $businessState;


    public function __construct(


        UserServiceInterface $userService,
        BusinessState        $businessState


    )
    {

        $this->userService = $userService;
        $this->businessState = $businessState;


    }


    /**
     *暂时通过名字来查询，同步socialite跟企业外部联系的数据
     */
    public function store(AddressRequest $request, Address $address)
    {


        $data = $request->filldata();
        if ($data['is_default']) {
            $default = Address::query()->where('user_id', $data['user_id'])->where('is_default', 1)->first();
            if ($default) {
                $default->update(['is_default' => 0]);
            }
        }
        $address->fill($data)->save();
        return $this->success(__('插入成功'));
    }

    public function delete(Request $request, $id)
    {

        Address::destroy($id);
        return $this->success(__('删除成功'));
    }

    public function update(AddressRequest $request, $id)
    {

        $address = Address::query()->where('id', $id)->firstOrFail();
        $data = $request->filldata();
        if ($data['is_default']) {
            $default = Address::query()->where('user_id', $data['user_id'])->where('is_default', 1)->first();
            if ($default) {
                $default->update(['is_default' => 0]);
            }
        }
        $address->fill($data)->save();
        return $this->success(__('地址成功'));
    }


    public function detail($id)
    {

        $address = Address::query()
            ->where('id', $id)->firstOrFail();
        return $this->successData(compact('address'));
    }

    public function edit($id)
    {

        $address = Address::query()
            ->where('id', $id)->firstOrFail();
        return $this->successData(compact('address'));
    }


    public function setDefaultAddress($id)
    {
        $userId = $this->id();
        $default = Address::query()->where('user_id', $userId)->where('is_default', 1)->first();
        if ($default) {
            $default->update(['is_default' => 0]);
        }
        $address = Address::query()->where('id', $id)->first();
        $address->update(['is_default' => 1]);
        return $this->success(__('设置默认地址成功'));

    }




}
